package com.lxw.demo.aspect;

import com.lxw.demo.annotation.Auth;
import com.lxw.demo.config.ResultCode;
import com.lxw.demo.role.service.Impl.RoleService;
import com.lxw.demo.role.vo.RoleVO;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

@Aspect
@Component
public class AuthAspect {

    @Autowired
    private RoleService roleService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("@annotation(com.lxw.demo.annotation.Auth)")
    public void LoginCut(){

    }

    @Before("LoginCut()")
    public void Login(JoinPoint joinPoint) throws AuthException {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            System.out.println(arg);
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        Method method = signature.getMethod();

        Auth auth = method.getAnnotation(Auth.class);
        String value = null;
        if (auth != null) {
            value = auth.value();
        }
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("Authorization");
        Object id = redisTemplate.opsForHash().get("Authorization", token);
        System.out.println((Integer) id);
        List<RoleVO> resources = roleService.findById((Integer) id);
        String finalValue = value;
        System.out.println("输出");
        System.out.println(finalValue);

        boolean flag = resources.stream().anyMatch(RoleVO -> RoleVO.getResourceName().equals(finalValue));
        if(!flag){
            throw new AuthException("无权访问");
        }



    }
}
